package com.lyc.utils;

import com.lyc.config.GaodeMapConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

@Component
public class GaodeMapUtil {

    // 高德地图配置
    private static GaodeMapConfig gaodeMapConfig;

    @Autowired
    public void setGaodeMapConfig(GaodeMapConfig gaodeMapConfig) {
        GaodeMapUtil.gaodeMapConfig = gaodeMapConfig;
    }

    /**
     * 发送GET请求到高德地图API
     *
     * @param endpoint API端点
     * @param params   请求参数
     * @return API响应结果
     */
    public static String sendGetRequest(String endpoint, Map<String, String> params) throws Exception {
        // 检查API密钥是否配置
        if (gaodeMapConfig == null || gaodeMapConfig.getApiKey() == null || gaodeMapConfig.getApiKey().isEmpty()) {
            throw new IllegalStateException("高德地图API密钥未配置");
        }
        
        // 创建可修改的参数Map副本
        Map<String, String> mutableParams = new HashMap<>(params);
        
        // 添加默认参数
        mutableParams.putIfAbsent("key", gaodeMapConfig.getApiKey());

        // 构建URI
        URIBuilder uriBuilder = new URIBuilder(gaodeMapConfig.getApiBaseUrl() + endpoint);
        for (Map.Entry<String, String> entry : mutableParams.entrySet()) {
            uriBuilder.setParameter(entry.getKey(), entry.getValue());
        }

        System.out.println("Request URL: " + uriBuilder.toString()); // 打印请求URL用于调试

        HttpGet httpGet = new HttpGet(uriBuilder.build());

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpGet)) {
            
            String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            System.out.println("Response status: " + response.getStatusLine().getStatusCode()); // 打印响应状态码
            System.out.println("Response body: " + result); // 打印响应内容
            
            return result;
        }
    }

    /**
     * 发送POST请求到高德地图API
     *
     * @param endpoint API端点
     * @param params   请求参数
     * @return API响应结果
     */
    public static String sendPostRequest(String endpoint, Map<String, String> params) throws Exception {
        // 检查API密钥是否配置
        if (gaodeMapConfig == null || gaodeMapConfig.getApiKey() == null || gaodeMapConfig.getApiKey().isEmpty()) {
            throw new IllegalStateException("高德地图API密钥未配置");
        }
        
        // 创建可修改的参数Map副本
        Map<String, String> mutableParams = new HashMap<>(params);
        
        // 添加默认参数
        mutableParams.putIfAbsent("key", gaodeMapConfig.getApiKey());

        // 构建POST数据
        StringJoiner joiner = new StringJoiner("&");
        for (Map.Entry<String, String> entry : mutableParams.entrySet()) {
            joiner.add(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) +
                    "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8));
        }

        String postData = joiner.toString();
        String url = gaodeMapConfig.getApiBaseUrl() + endpoint;
        
        System.out.println("Request URL: " + url); // 打印请求URL用于调试
        System.out.println("Request body: " + postData); // 打印请求体用于调试

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new StringEntity(postData, StandardCharsets.UTF_8));

        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {
            
            String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            System.out.println("Response status: " + response.getStatusLine().getStatusCode()); // 打印响应状态码
            System.out.println("Response body: " + result); // 打印响应内容
            
            return result;
        }
    }
}